package com.app.controller;

import cn.hutool.crypto.digest.MD5;
import cn.hutool.json.JSONObject;
import com.app.pojo.Status;
import com.app.pojo.UserInfo;
import com.app.service.IUserService;
import com.app.service.impl.CaptchaService;
import com.app.service.impl.UserService;
import com.app.utils.TokenManager;
import com.bby.CookieUtils;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.apache.taglibs.standard.lang.jstl.ELEvaluator;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController()
public class UserController {
    final int maxAge=30*60;
    private final IUserService userService;
    private final TokenManager tokenManager;
    private CaptchaService captchaService;

    public UserController(IUserService userService, TokenManager tokenManager, CaptchaService captchaService) {
        this.userService = userService;
        this.tokenManager = tokenManager;
        this.captchaService = captchaService;
    }

    /**
     * 用户登录，登录通过则添加记录，返回 cookie
     * @param email 用户邮箱
     * @param password 用户密码
     * @param response 响应
     * @return json数据
     */
    @PostMapping(value = "doLogin")
    public String loginUser(String email, String password,HttpServletResponse response){
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        password=MD5.create().digestHex(password);//将密码转为 md5

        String userId=userService.loginByEmail(email,password);
        JSONObject jsonObject=new JSONObject();
        if(userId!=null){//验证通过，返回token
            String token=tokenManager.addLoginState(userId,maxAge);
            Cookie cookie = new Cookie("token",token);
            response.addCookie(cookie);
            jsonObject.set("status",Status.SUCCESS);
        }else {
            jsonObject.set("status",Status.FAIL);
        }
        System.out.println("登录！");
        System.out.println(jsonObject);
        return jsonObject.toString();
    }
    /**
     * 用户注册，注册完成返回结果
     * @return json数据：captchaVerify : "OK"或者"FAIL", status 意义根据前者变化
     */
    @PostMapping(value = "doRegister")
    public String userRegister(String nickname,String password,String email,String captcha,HttpServletRequest request,HttpServletResponse response){
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        password=MD5.create().digestHex(password);//将密码转为 md5
        int verifyRes = captchaService.verifyCaptcha(request.getSession().getId(),captcha);
        JSONObject jsonObject=new JSONObject();
        if (verifyRes==Status.SUCCESS){//验证码验证通过
            jsonObject.set("captchaVerify","OK");
            jsonObject.set("status",userService.register(nickname,password,email));
        } else{
            jsonObject.set("captchaVerify","FAIL");
            jsonObject.set("status",verifyRes);
        }
        return jsonObject.toString();
    }

    @GetMapping(value = "doTest")
    public String doTest(HttpServletRequest request,HttpServletResponse response){
        System.out.println("doTest!");
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        JSONObject jsonObject=new JSONObject();
        jsonObject.set("aaa","assasas");
        jsonObject.set("bbb","assasas");
        jsonObject.set("ccc",123);
        jsonObject.set("ddd",true);
        return jsonObject.toString();
    }

    /**
     * 获取用户信息
     * @param request 请求，用于获得 cookie
     * @param response 响应
     * @return json数据
     */
    @GetMapping(value = "getUserInfo")
    public String getUserInfo(HttpServletRequest request,HttpServletResponse response){
        //获取用户信息
        String token=CookieUtils.getValue(request.getCookies(),"token");
        String userId=tokenManager.getUserId(token);

        JSONObject jsonObject=new JSONObject();
        if (userId==null){
            jsonObject.set("status", Status.USER_NOT_SIGNED_IN);
        }else {
            UserInfo userInfo = userService.getUserInfoById(userId);
            jsonObject.set("data",userInfo);
        }
        return null;
    }
}
